package dp.mobile.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

import android.content.Context;
import dp.mobile.system.Utilities;

public class Score implements Serializable{
	public Score(String pPlayerName, String levelName, int scoreValue, Date dateTaken){
		mPlayerName = pPlayerName;
		mLevelName	= levelName;
		mScoreValue	= scoreValue;
		mDateTaken	= dateTaken;
	}
	
	//Accessors
	public String getPlayerName() {
		return mPlayerName;
	}
	
	public String getLevelName(){
		return mLevelName;
	}
	
	public int getScoreValue(){
		return mScoreValue;
	}
	
	public Date getDateTaken(){
		return mDateTaken;
	}
	
	//PROPERTIES
	private String mPlayerName;
	private String mLevelName;
	private int mScoreValue;
	private Date mDateTaken;
	
	public static final String SCORE_EXTRA	= "SCORE";
	public static final String DATE_EXTRA	= "DATE_FORMAT";
	
	/**
	 * Auto-generated serialVersionUID 
	 */
	private static final long serialVersionUID = 1551556335107791715L;
	
	//STATIC METHOD
	public static void saveHighScore(Context context, Score scoreToSave){
		ScoreCollection scoresToSave;
		File file = null;
		FileOutputStream fos = null;
		ObjectOutputStream outStream = null;
		
		try {
			scoresToSave = Score.getAllHighScores(context, scoreToSave.getLevelName());
			
			file = new File(Utilities.HIGHSCORE_FOLDER + "/" + scoreToSave.getLevelName().replaceAll(" ", ""));
			if(!file.exists()) file.createNewFile();
			
			fos = new FileOutputStream(file);
			outStream = new ObjectOutputStream(fos);
			
			scoresToSave.addScore(scoreToSave);
			scoresToSave.sortAllScores();
			
			outStream.writeObject(scoresToSave);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(outStream != null)
					outStream.close();
				
				if(fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static ScoreCollection getAllHighScores(Context context, String levelName){
		ScoreCollection retval = new ScoreCollection(); 
    	File file = null;
    	FileInputStream fis = null;
		ObjectInputStream inStream = null;
		
		try {
			file = new File(Utilities.HIGHSCORE_FOLDER + "/" + levelName.replaceAll(" ", ""));
			if(file.exists()){
				fis = new FileInputStream(file);
				inStream = new ObjectInputStream(fis);
		        
				retval = (ScoreCollection) inStream.readObject();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(inStream != null)
					inStream.close();
				
				if(fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return retval;
    }
}
